package com.jiejie.university.controller;

import cn.hutool.core.date.DateUtil;
import com.jiejie.university.entity.Student;
import com.jiejie.university.service.StudentService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Resource
    private StudentService studentService;

    //查询全部学生
    @RequestMapping("/findStudentAll")
    public ModelAndView findStudentAll() {
        ModelAndView modelAndView = new ModelAndView();
        List<Student> list = this.studentService.findStudentAll();
        list.forEach(obj -> {
            obj.setBirthday(DateUtil.parse(DateUtil.formatDate(obj.getBirthday()), "yyyy-MM-dd"));
            obj.setEnroll(DateUtil.parse(DateUtil.formatDate(obj.getEnroll()), "yyyy-MM-dd"));
        });
        modelAndView.addObject("list", list);
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @RequestMapping("/deleteStudent")
    public ModelAndView deleteStudent(HttpServletRequest request){
        int id = Integer.parseInt(request.getParameter("id"));
        studentService.deleteStudent(id);
        return new ModelAndView("redirect:/student/findStudentAll");
    }

    //添加学生
    @GetMapping("/addStudent")
    public ModelAndView addStudent(Model model){
        model.addAttribute("student",new Student());
        return new ModelAndView("addStudent","stumodel",model);
    }
    @PostMapping("/add")
    @Transactional
    public ModelAndView add(Student student){
        studentService.addStudent(student);
        return new ModelAndView("redirect:/student/findStudentAll");
    }

    //更新学生
    @GetMapping("/sendid")
        public ModelAndView sendid(HttpServletRequest request,Model model){
        int id = Integer.parseInt(request.getParameter("id"));
        Student student = studentService.findStudentById(id);
        model.addAttribute("student",student);
        return new ModelAndView("updateStudent","stumodel",model);
    }

    @PostMapping("/update")
    public ModelAndView update(Student student){
        studentService.updataStudent(student);
        return new ModelAndView("redirect:/student/findStudentAll");
    }


    //根据学号id查找学生
    @PostMapping("/findUserById")
    public ModelAndView findUserById(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        Student student=this.studentService.findStudentById(id);
        modelAndView.addObject("student", student);
        modelAndView.setViewName("redirect:/student/findStudentAll");
        return modelAndView;
    }

}